package gruppe7.servlets;

import gruppe7.model.Model;
import gruppe7.model.ProviderException;
import gruppe7.model.User;
import gruppe7.model.UserException;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class UpdateBalanceServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		
		String userIdStr = request.getParameter("userId");
		String newBalanceStr = request.getParameter("balance");
		
		if (userIdStr == null | newBalanceStr == null) {
			out.println(getErrorXML("Missing parameters"));
		}

		else {
			
			int userId = -1;
			float balance = -1f;
			boolean inputOk = false;
			
			try {
				userId = Integer.valueOf(userIdStr).intValue();
				balance =  Float.valueOf(newBalanceStr).floatValue();
				inputOk = true;
			}
			
			catch (Exception e) {
				out.println(getErrorXML("Invalid parameters"));
			}
			
			if (inputOk) {
				try {
					Model model = Model.getInstance();
					User user = model.getUserById(userId);
					
					model.updateUserBalance(user, balance);
					out.println(getSuccessXML());
				}
				
				catch (UserException ue) {
					ue.printStackTrace();
				}
				
				catch (ProviderException pe) {
					throw new IOException(pe);
				}
			}
		}
		
	}
	
	private String getSuccessXML() {
		StringBuilder xml = new StringBuilder();
		
		xml.append("<response>");
		xml.append("<status error=\"false\"/>");
		xml.append("</response>");
		
		return xml.toString();
	}
	
	private String getErrorXML(String msg) {
		
		StringBuilder xml = new StringBuilder();
		
		xml.append("<response>");
		xml.append(String.format("<status error=\"true\" value=\"%s\" />", msg));
		xml.append("</response>");
		
		return xml.toString();
		
	}

}
